﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVCSayDemo.Data;
using MVCSayDemo.Models;
using MVCSayDemo.ViewModel;
using MVCSayDemo.paramModel;

namespace MVCSayDemo.Controllers
{
    public class UsersController : Controller
    {
        private UsersContext db = new UsersContext();

        public ActionResult Index()
        {
            var userList = db.Users.ToList();
            
            if (Session["Username"] == null)
            {
                return View();
            }
            else
            {
                var sessionId = userList.SingleOrDefault(x => x.Username == Session["Username"].ToString()).Id;
                return RedirectToAction("Index" + sessionId,"Users");
            }
        }


        public ActionResult Register()
        {
            return View("Register");
        }

        public ActionResult Login()
        {
            return View("Login");
        }
        [HttpPost]
        public ActionResult RegisterDone(RegisterModel registerModel)
        {
            var username = registerModel.Username.Trim();
            var password = registerModel.Password.Trim();
            var repetitionPassword = registerModel.RepetitionPassword.Trim();

            //decimal result;
            if (username.Length > 0 && password.Length > 0 && password.Equals(repetitionPassword))
            {
                var user = db.Users.Where(x => x.Username.Equals(username)).SingleOrDefault();
                if(user != null)
                {
                    return Content("<script>alert('用户名已存在');location.href='Register';</script>");
                }
                else
                {
                    db.Users.Add(new Users
                    {
                        Username = username,
                        Password = password,
                        CreateAt = DateTime.Now,
                        UpdateAt = DateTime.Now,
                        Version = 0
                    });

                    db.SaveChanges();
                    return Content("<script>alert('注册成功');location.href='Login';</script>");
                }
            }
            else
            {
                return Content("<script>alert('用户名或密码不能为空，并且两次密码应一致');location.href='Register';</script>");
            }
        }

        [HttpPost]
        public ActionResult LoginDone(LoginModel loginModel)
        {

            var username = loginModel.Username.Trim();
            var password = loginModel.Password.Trim();
            var userList = db.Users.ToList();
            if (username.Length > 0 && password.Length > 0)
            {


                var user = db.Users.Where(x=>x.Username.Equals(username) && x.Password.Equals(password)).SingleOrDefault();
                if (user != null)
                {
                    Session["Username"] = username;
                    var sessionId = userList.SingleOrDefault(x => x.Username == Session["Username"].ToString()).Id;
                    return Content("<script>location.href='/';</script>");
                }
                else
                {
                    return Content("<script>alert('用户名或密码不正确');location.href='Login';</script>");
                }
            }
            else
            {
                return Content("<script>alert('用户名或密码不能为空');location.href='Login';</script>");
            }
        }

        // GET: Users/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users users = db.Users.Find(id);
            if (users == null)
            {
                return HttpNotFound();
            }
            return View(users);
        }

        // GET: Users/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Users/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Username,Password,CreateAt,UpdateAt,Version,Remarks")] Users users)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(users);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(users);
        }

        // GET: Users/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users users = db.Users.Find(id);
            if (users == null)
            {
                return HttpNotFound();
            }
            return View(users);
        }

        // POST: Users/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Username,Password,CreateAt,UpdateAt,Version,Remarks")] Users users)
        {
            if (ModelState.IsValid)
            {
                db.Entry(users).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(users);
        }

        // GET: Users/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users users = db.Users.Find(id);
            if (users == null)
            {
                return HttpNotFound();
            }
            return View(users);
        }

        // POST: Users/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Users users = db.Users.Find(id);
            db.Users.Remove(users);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
